package wjh.blog.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import wjh.blog.exception.MsgException;
import wjh.blog.pojo.Blog;
import wjh.blog.pojo.BlogType;
import wjh.blog.service.BlogService;
import wjh.blog.util.PageView;

/**
 * 博客控制器
 * @author Administrator
 *
 */
@Controller
@RequestMapping("blog")
public class BlogController {
	Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private BlogService blogService;
	
	@RequestMapping("list")
	public String list(){
		return "list";
		
	}
	
	@RequestMapping("getist/{typeId}/{pageNum}")
	public String getlist(@PathVariable int typeId, 
			@PathVariable int pageNum,Model model){
		Page<?> page = PageHelper.startPage(pageNum, 5);
		List<Blog> blogs = blogService.getBlogs(typeId);
		
		PageView pageView = new PageView(page.getPages(), pageNum);
		model.addAttribute("pageView", pageView);
		model.addAttribute("typeId", typeId);
		model.addAttribute("blogs", blogs);
		return "blog/_list";
	}
	
	
	@RequestMapping("publish")
	public String publish(Model model){
		List<BlogType> types=blogService.getTypes();
		model.addAttribute("types", types);
		
		return "publish";
	}
	
	@RequestMapping("addBlog")
	public String addBlog(Blog blog,Model model){
		try{
			blogService.addBlog(blog);
		}catch(MsgException e){
			model.addAttribute("msg", e.getMessage());
			return publish(model);
		}
		model.addAttribute("msg", "发布成功");
		blog.clear();
		return publish(model);
	}
	@RequestMapping("test")
	@ResponseBody
	public String test(){
		Blog blog = new Blog();
		BlogType type= new BlogType();
		type.setId(1);
		blog.setType(type);
		String content = "测试内容,";
		for(int i=0;i<88;i++){
			content+="测试内容,";
		}
		blog.setContent(content);
		blog.setTitle("测试内容标题");
		for(int i=0;i<100;i++){
			blogService.addBlog(blog);
		}
	/*	BlogComment comment = new BlogComment();
		String content = "测试内容";
		for(int i=0;i<6;i++){
			content+="测试内容";
		}
		comment.setContent(content);
		Blog blog = new Blog();
		blog.setId(1);
		comment.setBlog(blog);
		for(int i=0;i<100;i++)
			blogService.addComment(comment);*/
	/*	Page<?> page = PageHelper.startPage(1, 10);
		@SuppressWarnings("unused")
		Page<Blog> blogs = (Page<Blog>) blogService.getBlogs();
		*/
		return "test";
	}
	

}
